package org.jgs1904.tieba.service.impl;

import org.jgs1904.tieba.entity.Post;
import org.jgs1904.tieba.entity.User;
import org.jgs1904.tieba.repository.PostRepository;
import org.jgs1904.tieba.repository.UserRepository;
import org.jgs1904.tieba.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Optional;

/**
 * @author junki
 * @date 2020/5/12 14:40
 */
@Service
public class PostServiceImpl implements PostService {

    @Autowired
    private PostRepository postRepository;

    @Autowired
    private UserRepository userRepository;

    @Override
    public Page<Post> getPage(Post post, int pageSize, int pageNum) {

        if (StringUtils.isEmpty(post.getTitle())) {
            post.setTitle(null);
        }
        if (StringUtils.isEmpty(post.getSummary())) {
            post.setSummary(null);
        }
        if (StringUtils.isEmpty(post.getContent())) {
            post.setContent(null);
        }

        Example<Post> postExample = Example.of(post);

        PageRequest pageRequest = PageRequest.of(pageNum, pageSize, Sort.by(Sort.Direction.DESC, "createTime"));

        return postRepository.findAll(postExample, pageRequest);
    }

    @Override
    public Post getOneById(Long id) {
        return postRepository.findById(id).orElse(null);
    }

    @Override
    public Post add(Post post) {
        Optional<User> userOptional = userRepository.findById(post.getUser().getId());
        if (!userOptional.isPresent()) {
            return null;
        }
        post.setUser(userOptional.get());

        post.setCreateTime(new Date());

        return postRepository.save(post);
    }

}
